﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Microsoft.Xna.Framework;

namespace Babylon.Animations.Skeleton
{
    public class SkeletonKeyFrame
    {
        public float KeyTime { get; set; }

        public Matrix[] Transforms { get; set; }
    }
    public class AnimationClip
    {
        static Matrix _matrix0 = new Matrix(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
        public float Duration { get; set; }
        public LinkedList<SkeletonKeyFrame> KeyFrames { get; set; }
        public AnimationClip(int boneCount, IEnumerable<Serialization.BoneKeyFrame> boneKeyFrames)
        {
            KeyFrames = new LinkedList<SkeletonKeyFrame>();

            var grouped = boneKeyFrames.GroupBy(kf => kf.KeyTime).ToList();
            foreach (var g in grouped)
            {
                var skFrame = new SkeletonKeyFrame {KeyTime = g.Key, Transforms = new Matrix[boneCount]};
                foreach (var boneKeyFrame in g)
                {
                    skFrame.Transforms[boneKeyFrame.BoneIndex] = boneKeyFrame.Transform;
                }
                KeyFrames.AddLast(skFrame);
                for(int i=0;i<skFrame.Transforms.Length;i++)
                {
                    if(skFrame.Transforms[i] == _matrix0)
                    {
                        skFrame.Transforms[i] = KeyFrames.Last.Previous.Value.Transforms[i];
                    }
                }
            }

            Duration = KeyFrames.Last.Value.KeyTime;
        }
    }
}
